<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'mo:task:mesOrderTask:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="85%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }}</span>
    </template>
    <BasicForm @register="registerForm">
      <template #taskList>
        <BasicTable @register="registerTaskTable" @row-click="handleTaskRowClick" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMoRepMesOrderTaskRepForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { mesOrderTaskRep } from '/@/api/mes/mo/rep/mesOrderTaskRep';
  import { BasicTable, useTable } from '/@/components/Table';
  import { basOperatorTreeData } from '/@/api/bas/mes/operator/basOperator';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('mo.rep.mesOrderTaskRep');
  const { showMessage } = useMessage();
  const record = ref<MesOrderTaskRep>({} as MesOrderTaskRep);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('报工登记'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t(''),
      field: 'taskList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'taskList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    record.value.taskList = data;
    setTaskTableData(record);
    setDrawerProps({ loading: false });
  });

  const [registerTaskTable, taskTable, getColumns, getDataSource] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleTestDataChildDelete.bind(this, record),
          },
          auth: 'test:testData:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setTaskTableData(_res: Recordable) {
    taskTable.setColumns([
      {
        title: t('订单号'),
        dataIndex: 'scOrder.code',
        width: 70,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('行号'),
        dataIndex: 'scOrder.sortNum',
        width: 40,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('工序编码'),
        dataIndex: 'operCode',
        width: 60,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('工序名称'),
        dataIndex: 'basOper.name',
        width: 60,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('存货编码'),
        dataIndex: 'invCode',
        width: 80,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        width: 150,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('任务数'),
        dataIndex: 'iqty',
        width: 60,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('计件单价'),
        dataIndex: 'iprice',
        width: 60,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('报工数'),
        dataIndex: 'bgQty',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'InputNumber',
        editRule: true,
        editable: true,
        fixed: 'right',
      },
      {
        title: t('操作工'),
        dataIndex: 'operator',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: basOperatorTreeData,
          params: { isLoadUser: true, userIdPrefix: '' },
          canSelectParent: false,
          allowClear: true,
        },
        editRule: true,
        editable: true,
        fixed: 'right',
      },
    ]);
    taskTable.setTableData(record.value.taskList || []);
  }

  function handleTaskRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleTestDataChildDelete(record: Recordable) {
    taskTable.deleteTableDataRecord(record);
  }

  async function getTaskList() {
    let taskListValid = true;
    let taskList: Recordable[] = [];
    for (const record of taskTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        taskListValid = false;
      }
      taskList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of taskTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      taskList.push({
        ...record,
        status: '1',
      });
    }
    if (!taskListValid) {
      throw { errorFields: [{ name: ['taskList'] }] };
    }
    return taskList;
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      const taskList = await getTaskList();
      const bgList = taskList.map((e) => ({
        taskId: e.id,
        iqty: e.bgQty,
        operator: e.operator,
      }));
      // console.log('submit', params, data, record);
      const res = await mesOrderTaskRep(bgList);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style>
  .jeesite-editable-cell__action {
    display: none;
  }
  /* .ant-select-show-search {
    width: 100% !important ;
  } */
  .edit-cell-align-center {
    width: 100% !important;
  }
  .edit-cell-align-left {
    width: 100% !important;
  }
</style>
